﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace BneyBaruch.Ingest.Core.ServiceProcess.Diagnostics
{
    public class ServiceRunner : ServiceDebuggerHelper.ServiceRunner
    {
        #region Fields

        private bool _isStarted = false;
        private Button startButton = null;
        private Button stopButton = null;
        private DebuggableService _debuggableService = null;

        #endregion

        #region Constructors

        public ServiceRunner(DebuggableService service,bool startOnInitialization)
            : base(service)
        {
            _debuggableService = service;

            InitializeButtons();

            if (startOnInitialization)
            {
                if (startButton != null)
                {
                    startButton.PerformClick();
                }
            }
        }

        #endregion

        #region Private Methods

        private void InitializeButtons()
        {
            Control[] foundStopButton = this.Controls.Find("stopButton", true);
            if (foundStopButton != null && foundStopButton.Length == 1)
            {
                stopButton = foundStopButton[0] as Button;
                if (stopButton != null)
                {
                    stopButton.Click += new EventHandler(stopButton_Click);
                }
            }

            Control[] foundStartButton = this.Controls.Find("startButton", true);
            if (foundStartButton != null && foundStartButton.Length == 1)
            {
                startButton = foundStartButton[0] as Button;
                if (startButton != null)
                {
                    startButton.Click += new EventHandler(startButton_Click);
                }
            }
        }

        #endregion

        #region Buttons Clicks

        void startButton_Click(object sender, EventArgs e)
        {
            _isStarted = true;
            if (startButton != null)
                startButton.Enabled = false;
            if (stopButton != null)
                stopButton.Enabled = true;
        }

        void stopButton_Click(object sender, EventArgs e)
        {
            _isStarted = false;
            if (startButton != null)
                startButton.Enabled = true;
            if (stopButton != null)
                stopButton.Enabled = false;
        }

        #endregion

        #region OnClosing Form

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            if (_isStarted)
            {
                _debuggableService.StopService();
            }
        }

        #endregion
    }
}
